package com.zoro.barn.commons.db.autopage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author zhaoxingwu
 */
@EnableConfigurationProperties(BarnPagerProperties.class)
public class AutoPageConfig {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final BarnPagerProperties barnPagerProperties;
    private final ResponsePageAdvice responsePageAdvice;



    public AutoPageConfig(BarnPagerProperties barnPagerProperties) throws ClassNotFoundException {
        this.barnPagerProperties = barnPagerProperties;

        if (barnPagerProperties.getSupportClass() == null) {

            this.responsePageAdvice = new ResponsePageAdvice(barnPagerProperties.getCurrent(), barnPagerProperties.getCount());
        } else {
            Class<?> supportClass = Class.forName(barnPagerProperties.getSupportClass());
            this.responsePageAdvice = new ResponsePageAdvice(supportClass, barnPagerProperties.getCurrent(), barnPagerProperties.getCount());
        }
    }


    @Bean
    public PageParamFilter pageParamFilter() {
        return new PageParamFilter(barnPagerProperties.getCurrent(), barnPagerProperties.getPageSize());
    }

    @Bean
    public BarnPagePlugin barnPagePlugin() {
        return new BarnPagePlugin();
    }

    @Bean("responsePageAdvice")
    public ResponseBodyAdvice<?> responsePageAdvice() {
        return new NestedResponsePageParamAdvice();
    }

    @Bean
    public PageInitBean pageInitBean() {
        return new PageInitBean();
    }

    @RestControllerAdvice
    @Order(200)
    private class NestedResponsePageParamAdvice implements ResponseBodyAdvice<Object> {


        @SuppressWarnings("unchecked")
        @Override
        public boolean supports(MethodParameter returnType, Class converterType) {
            return responsePageAdvice.supports(returnType, converterType);
        }
        @SuppressWarnings("unchecked")
        @Override
        public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                      Class selectedConverterType, ServerHttpRequest request,
                                      ServerHttpResponse response) {

            return responsePageAdvice.beforeBodyWrite(body, returnType, selectedContentType, selectedConverterType,
                    request, response);
        }

    }
}
